package service

import (
	"api-gateway/basic/config"
	__ "api-gateway/basic/proto/rpc"
	"api-gateway/handler/request"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

func GetMemberList(c *gin.Context) {
	mer, err := config.VideoRpcClient.GetMemberList(c, &__.GetMemberListReq{})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "查询会员套餐列表成功", "data": gin.H{
		"list": mer.List,
	}})
	return
}

func PayMember(c *gin.Context) {
	var form request.PayMember
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误"})
		return
	}
	mer, err := config.VideoRpcClient.PayMember(c, &__.PayMemberReq{
		UserId:   int64(form.UserId),
		MemberId: int64(form.MemberId),
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "生成支付Url,前往支付", "data": gin.H{
		"payUrl": mer.PayUrl,
	}})
	return
}

func AliPayCallback(c *gin.Context) {
	log.Println("---------------------------收到支付宝回调----------------------------")
	err := c.Request.ParseForm()
	if err != nil {
		return
	}
	form := c.Request.PostForm
	orderSn := form["out_trade_no"][0]
	tradeStatus := form["trade_status"][0]
	_, err = config.VideoRpcClient.AliPayCallback(c, &__.AliPayCallbackReq{
		OrderSn:     orderSn,
		TradeStatus: tradeStatus,
	})
	if err != nil {
		log.Println("支付失败" + err.Error())
	}
	log.Println("支付成功")
	log.Println("---------------------------支付宝回调结束----------------------------")
	_, err = c.Writer.Write([]byte("success"))
	if err != nil {
		return
	}
	return
}

func GetUserMember(c *gin.Context) {
	var form request.GetUserMember
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误"})
		return
	}
	user, err := config.VideoRpcClient.GetUserMember(c, &__.GetUserMemberReq{
		UserId: int64(form.UserId),
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "查询会员状态成功", "data": gin.H{
		"Username":         user.Username,
		"MemberStatus":     user.MemberStatus,
		"MemberExpireTime": user.MemberExpireTime,
	}})
	return
}
